<template>
  <div class="hm-cover">
      <!-- 图片按钮 -->
      <div class="btn_img">
          <img :src="currentImage" @click="openDialog">
      </div>
      <el-dialog title="上传封面" :visible.sync="dialogVisible" width="960px">
          <!-- tab栏 -->
          <el-tabs v-model="activeName" type="card">
              <el-tab-pane label="素材库" name="picture">
                  <el-radio-group v-model="collect" @change="change">
                      <el-radio-button :label="false">全部</el-radio-button>
                      <el-radio-button :label="true">收藏</el-radio-button>
                  </el-radio-group>
                  <el-row :gutter="10">
                      <el-col :span="6" v-for="item in pictures" :key="item.id">
                          <el-image
                            :class="{selected: item.url === selectedImageUrl}"
                            @click="selectImage(item.url)"
                            style="height:140px; width: 100%"
                            :src="item.url"
                            fit="cover"
                            >
                          </el-image>
                      </el-col>
                  </el-row>
                  <el-pagination
                    background
                    layout="total, prev, pager, next, jumper"
                    :total="total"
                    :page-size="per_page"
                    :current-page="page"
                    @current-change="handleCurrentChange">
                   </el-pagination>
              </el-tab-pane>
              <el-tab-pane label="上传图片" name="upload">
                  <el-upload
                  class="avatar-uploader"
                  action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
                  :headers="headers"
                  name="image"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleError"
                  :before-upload="beforeAvatarUpload"
                  >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
                  <i v-else class="el-icon-plus avatar-uploader-icon" ></i>
                  </el-upload>
              </el-tab-pane>
          </el-tabs>
          <template v-slot:footer>
              <span class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="onConfirm">确 定</el-button>
              </span>
          </template>
      </el-dialog>
  </div>
</template>

<script>
import { reqPictures } from '@/api/pictures'
import { getToken } from '@/utils/storage'
import image from '@/assets/default.png'
export default {
  props: ['value'],
  data () {
    return {
      dialogVisible: false,
      activeName: 'picture',
      collect: false,
      pictures: [],
      page: 1,
      per_page: 8,
      total: 0,
      // 选中的图片的地址
      selectedImageUrl: '',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 保存上传成功的图片
      imageUrl: '',
      currentImage: this.value || image
    }
  },
  // 监听属性的变化
  watch: {
    value () {
      this.currentImage = this.value || image
    }
  },
  methods: {
    openDialog () {
      this.dialogVisible = true
      this.getPictures()
    },
    async getPictures () {
      const res = await reqPictures({
        page: this.page,
        per_page: this.per_page,
        collect: this.collect
      })
      const { results, total_count } = res.data.data
      this.pictures = results
      this.total = total_count
    },
    handleCurrentChange (value) {
      this.page = value
      this.getPictures()
    },
    change () {
      this.page = 1
      this.getPictures()
    },
    selectImage (url) {
      console.log('点击了', url)
      this.selectedImageUrl = url
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = res.data.url
      this.$message.success('上传成功')
    },
    handleError () {
      this.$message.error('服务器繁忙,请稍后尝试')
    },
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    onConfirm () {
      /*
        1. 判断当前tab的值 是 picture或者是upload
        2. 如果是picture，判断是否选中图片
      */
      if (this.activeName === 'picture') {
        if (!this.selectedImageUrl) {
          return this.$message.error('请选择一张图片')
        } else {
          this.currentImage = this.selectedImageUrl
        }
      } else if (this.activeName === 'upload') {
        if (!this.imageUrl) {
          return this.$message.error('请上传图片')
        } else {
          this.currentImage = this.imageUrl
        }
      }
      this.dialogVisible = false
      // 把current传递给父组件
      this.$emit('input', this.currentImage)
    }
  }
}
</script>

<style lang="less" scoped>
// 图片按钮
.btn_img {
    width: 150px;
    height: 150px;
    border: 1px dashed #ddd;
    img {
        width: 100%;
        height: 100%;
        display: block;
    }
}
.el-row {
  margin-top: 10px;
  .el-col {
    margin-top: 8px;
  }
}
.selected {
  position: relative;
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    // background-color: rgba(0, 0, 0, .5);
    // background-image: url('~@/assets/selected.png');
    // background-size: 80px 80px;
    // background-repeat: no-repeat;
    // background-position: center center;
    background: rgba(0, 0, 0, .5) url('~@/assets/selected.png') no-repeat center center / 80px 80px;
    z-index: 99;
  }
}
</style>
